cmake_minimum_required(VERSION 2.6)
set(CMAKE_BUILD_TYPE ${KONOHA_BUILD_TYPE})

project(sql)
find_program(MYSQL_CONFIG NAMES mysql_config)

if(MYSQL_CONFIG)

execute_process(
	COMMAND ${MYSQL_CONFIG} --libs
	OUTPUT_VARIABLE HAVE_LIBMYSQL
	OUTPUT_STRIP_TRAILING_WHITESPACE
)
execute_process(
	COMMAND ${MYSQL_CONFIG} --include
	OUTPUT_VARIABLE MYSQL_INCLUDE_DIR
	OUTPUT_STRIP_TRAILING_WHITESPACE
)
string(REPLACE "-I" "" HAVE_MYSQL_H ${MYSQL_INCLUDE_DIR})

if(HAVE_MYSQL_H)
	add_definitions(-DK_USING_PKG_MYSQL)
	set(MessageLibs ${MessageLibs} mysql PARENT_SCOPE)
endif(HAVE_MYSQL_H)

endif(MYSQL_CONFIG)

find_library(HAVE_LIBSQLITE3 sqlite3)

if(HAVE_LIBSQLITE3)
	add_definitions(-DK_USING_PKG_SQLITE3)
endif(HAVE_LIBSQLITE3)

if(HAVE_MYSQL_H OR HAVE_LIBSQLITE3)

set(PACKAGE_SCRIPT_CODE sql.k)
set(PACKAGE_SOURCE_CODE
	src/mysql.c
	src/sqlite.c
	src/dbapi.c
	src/query.c
)

set(PACKAGE_NAME    ${PROJECT_NAME})
set(PACKAGE_VERSION ${VERSION_MAJOR}.${VERSION_MINOR}.${VERSION_PATCH})
set(PACKAGE_STRING  ${CMAKE_PROJECT_NAME}-${PACKAGE_VERSION})
set(KONOHA_PACKAGE_DIR konoha/package/${KONOHA_VERSION}/konoha.${PROJECT_NAME})

set(INCLUDE_DIRS ${INCLUDE_DIRS} ${CMAKE_CURRENT_SOURCE_DIR}
		${CMAKE_CURRENT_SOURCE_DIR}/include  ${CMAKE_CURRENT_BINARY_DIR}
		${KONOHA_INCLUDE_DIRS} ${HAVE_MYSQL_H}
		)
include_directories(${INCLUDE_DIRS})

add_definitions(-D_SETUP)

add_library(${PACKAGE_NAME} SHARED ${PACKAGE_SOURCE_CODE})
set_target_properties(${PACKAGE_NAME} PROPERTIES PREFIX "")
target_link_libraries(${PACKAGE_NAME} konoha ${HAVE_LIBMYSQL} ${HAVE_LIBSQLITE3})

install(TARGETS ${PACKAGE_NAME} DESTINATION ${KONOHA_PACKAGE_DIR})
install(FILES ${CMAKE_CURRENT_SOURCE_DIR}/${PACKAGE_SCRIPT_CODE} DESTINATION ${KONOHA_PACKAGE_DIR})

endif(HAVE_MYSQL_H OR HAVE_LIBSQLITE3)

